import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import global from '@/global/global.js'
import layer from 'vue-layer'
import HelloWorld from '@/components/HelloWorld'
import main from "@/pages/main"
import login from "@/pages/login/login"
import myList from "@/pages/trademark/myList"
import goodList from "@/pages/commodity/list"
import goodDetail from "@/pages/commodity/detail"
import application from "@/pages/trademark/application"
import declareList from "@/pages/patent/declareList"
import declareDetail from "@/pages/patent/declareDetail"
import inDeclaration from "@/pages/patent/inDeclaration"
import inDeclarationDetail from "@/pages/patent/inDeclarationDetail"
import myproject from "@/pages/government/myproject"
import declareProject from "@/pages/government/declareProject"
import personInfo from "@/pages/person/personInfo"
import  bindInfo  from "@/pages/person/bindInfo"
import listProject from "@/pages/government/listProject"
import listProjectDetail from "@/pages/government/listProjectDetail"
import softList from "@/pages/soft/softList"
import http from "../api/http"
import  Axios from 'axios'

Vue.use(Router)
Vue.prototype.global=global;
Vue.prototype.$layer = layer(Vue,{msgtime:3});//消失时间为3秒

if(localStorage.getItem('token')){
	store.commit('set_token', localStorage.getItem('token'))
}

let router=new Router({
  /*mode: 'history',*/
  routes: [
  	{
      path: '/',
      name: 'main',
      component: main,
      redirect:'personInfo',//设置页面一进来就显示的页面，即重定向到myList组件
      meta:{
      	requireAuth:true
      },
      children:[
      	{
			  	path:"myList",
			  	name:"myList",
			  	component:myList,
			  	meta: {title:'我的商标',requireAuth:true}
		},{
			path:"goodList",
			name:"goodList",
			component:goodList,
			meta:{requireAuth:true},
		},{
			path:"goodDetail",
			name:"goodDetail",
			component:goodDetail,
			meta:{requireAuth:true},
		},{
			path:"application",
			name:"application",
			component:application,
			meta:{requireAuth:true},
		},{
			path:"declareList",
			name:"declareList",
			component:declareList,
			meta:{requireAuth:true},
		},{
			path:"declareDetail",
			name:"declareDetail",
			component:declareDetail,
			meta:{requireAuth:true},
		},{
			path:"inDeclaration",
			name:"inDeclaration",
			component:inDeclaration,
			meta:{requireAuth:true},
		},{
			path:"inDeclarationDetail",
			name:"inDeclarationDetail",
			component:inDeclarationDetail,
			meta:{requireAuth:true},
		},{
			path:"myproject",
			name:"myproject",
			component:myproject,
			meta:{requireAuth:true},
		},{
			path:"declareProject",
			name:"declareProject",
			component:declareProject,
			meta:{requireAuth:true},
		},{
			path:"personInfo",
			name:"personInfo",
			component:personInfo,
			meta:{requireAuth:true},
		},{
			path:"listProject",
			name:"listProject",
			component:listProject,
			meta:{requireAuth:true},
		},{
			path:"listProjectDetail",
			name:"listProjectDetail",
			component:listProjectDetail,
			meta:{requireAuth:true},
		},{
        path:"softList",
        name:"softList",
        component:softList,
        meta:{requireAuth:true},
        }
      ]
    },
	  {
	    	path:"/bindInfo",
	    	name:"bindInfo",
	    	component:bindInfo
	  },
    {
      path:"/login",
      name:"login",
      component:login
    },

  ]
})

Vue.prototype.getUrlParam=function (name) {
  decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}
//跳转之前判断
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requireAuth)){  // 判断该路由是否需要登录权限
       if(localStorage.getItem("token")){
         next();
       }else {
      //微信登录逻辑
      let ua = window.navigator.userAgent.toLowerCase();
      let isweiChat = ua.match(/MicroMessenger/i) == 'micromessenger';
     // alert(isweiChat)
      //是否微信登录
        /* next({
           path: '/?from=singlemessage#/&response_type=code&scope=snsapi_userinfo&state=123',
           query: {redirect: to.fullPath}
           // 将跳转的路由path作为参数，登录成功后跳转到该路由
         });*/
      if (isweiChat) {
        //拿到微信登录的openid
        if (localStorage.getItem("openid")) {
          //next('/bindInfo');
          router.push("/bindInfo");//2018-10-16修改的
          // next();
          return;
        }
        // const code1 = this.getUrlParam("code");
        let code = decodeURIComponent((new RegExp('[?|&]' + "code" + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
        console.log(code);
        //  window.location.href).code // 截取url上的code ,可能没有,则返回''空字符串
        if (!code || code == null) {
          code = "";
        }
        Axios.post(global.url + '/api/weichat/userauth?code=' + code,).then(res => {
          let data = res.data;
          console.log(res)
          console.log(data.code)
          // 返回用户信息
          if (data.code == 200) {
            store.commit('set_token', data.data.token["token"]);
            store.commit('set_refleshToken', data.data.token["refleshToken"]);
            localStorage.setItem('token',  data.data.token["token"]);
            localStorage.setItem('refleshToken',   data.data.token["refleshToken"]);
            let userInfo = JSON.stringify(data.data.userInfo);
            localStorage.setItem('userInfo', userInfo);
            //let redirect = decodeURIComponent(this.$route.query.redirect || '/');
           // this.$router.push({ path: redirect });//登录成功后跳转路由
            //router.push('/');//获取到用户信息才跳转到首页
            next();
          } else {
            // 此状态根据业务需求 可能不存在,仅仅存在openid
            if (data.code == 201) {
              let openid = data.data.token["openId"];
              let  headImg=data.data.token["headImg"];
              store.commit('set_openid', openid);
              console.log("详情" + store.state.openid);
              localStorage.setItem('openid', openid);
              localStorage.setItem('headImg', headImg);
              next({
	            path: '/bindInfo',
	            query: {redirect: to.fullPath}
	            // 将跳转的路由path作为参数，登录成功后跳转到该路由
	          })
              //router.push("/bindInfo");//2018-10-16修改的
              //next('/bindInfo')
            }
            //没关注跳转关注页面
            if (data.code == 203) {
              let toUrl ="https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzUxMDYzNTI4Mg==&scene=126#wechat_redirect";
              /* data.data.token["toUrl"]*/;
              //this.$layer.confirm('没关注科技号，跳转关注接收进度消息', function(){
                window.location.href =toUrl;
            //  });

            }
            // 上面的获取用户信息接口,如果cookie,session拿不到用户信息,且传递的code为空,则跳转到微信授权页面
            if (data.code == 202) {
              // 这个redirectUrl用 当前页路径或者tof.fullPath(将要进入的路径)
              let redirectUrl = window.location.href;
             // alert(redirectUrl)
              redirectUrl = encodeURIComponent(redirectUrl)
              console.log(redirectUrl)

              const appid = 'wx7fc0625cd44b0687';
              window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
            }
          }
        }).catch(error => {
          console.log(error);
          next({
            path: '/login',
            query: {redirect: to.fullPath}
            // 将跳转的路由path作为参数，登录成功后跳转到该路由
          })
        })
        // 获取用户信息,后端可首先通过cookie,session等判断,没有信息则通过code获取

      } else {
        next({
          path: '/login',
          query: {redirect: to.fullPath}
          // 将跳转的路由path作为参数，登录成功后跳转到该路由
        })
      }
    }
  }else {
    next();
  }
})


/*/!* eslint-disable no-new *!/
const Bus = new Vue()
var app=new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>',
  data:{
    Bus
  },methods:{
    isWechat:function () {
      let ua = window.navigator.userAgent.toLowerCase();
      return ua.match(/MicroMessenger/i) == 'micromessenger';
    }
  }
})*/

export default router;
